/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name: 'step_filter',
			title: 'step过滤',
			type: 'LineEdit'
		},
		{
			name : 'auto_save',
			title : '自动保存',
			type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'Yes'},
					{name:'no',text:'No'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-20 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> pad对齐 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("================================>线转pad");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step_filter:'net.+',
		step2:"net",
		units: "mm",
		auto_save: "no"
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}

	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }

	var stepList = GEN.getStepList({job:job})
	// step过滤
    var stepListFilter = stepList.filter(function(step){
		var regexp = new RegExp(par.step_filter,"ig")
		return regexp.test(step)
	})
	if (stepListFilter.length == 0 && par.step2) {
		stepListFilter = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	if(stepListFilter.length == 0) { throw "未发现step:"+par.step_filter }
	var tmplayer = [
		{sig:"gtl",sm:"gts"},
		{sig:"gbl",sm:"gbs"}
	]
	tmplayer = tmplayer.filter(function(item){
		return GEN.isLayerExists({job:job,layer:item.sig}) && GEN.isLayerExists({job:job,layer:item.sm})
	})

	stepListFilter.forEach(function(step){
        GEN.openStep({job:job,name:step})

        //料号初始化
		GEN.clearLayers();  //清除层显示
		GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响
		//操作模式初始化
		GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.units({ type: par.units });  //单位初始化
        GEN.zoomHome();  //窗口显示回到原始位置
        
		if(tmplayer.length){
			tmplayer.forEach(function(item){
				var sig = item.sig;
				var sm = item.sm;
				if(GEN.isLayerExists({job:job, layer:"turn_pad_turn"})){GEN.deleteLayer({job:job, layer:"turn_pad_turn"})}
				GEN.clearLayers();  //清除层显示
				GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响
				GEN.workLayer({name:sm,display_number:2,clear_before:'yes'})  // 所有物件转pad
				GEN.selectByFilter({feat_types:"pad"})
				GEN.selReverse()
				if(GEN.getSelectCount()>0){
					// 将选择的转pad
					GEN.COM("sel_cont_resize,accuracy=0,break_to_islands=yes,island_size=0,hole_size=0,drill_filter=no,corner_ctl=yes")
					GEN.units({type:"inch"})
					GEN.selectByFilter({feat_types:"pad"})
					GEN.selReverse()
					GEN.COM("sel_cont2pad,match_tol=1,restriction=,min_size=0.01,max_size=100000,suffix=+++")
					GEN.units({ type: par.units });  //单位初始化
				}
				GEN.workLayer({name:sig,display_number:2,clear_before:'yes'}) 
				GEN.runSingleDfm({
					chklist : "valor_cleanup_auto_subst",
					erf     : "Outers",
					show_res: 'no',
					params  : {
						pp_layer  :'.affected',  	 pp_in_selected:'All',
						pp_min_smd:304.8,		 	 pp_max_smd:7620,
						pp_tol	 :2.54,pp_ref_sm:sm,
						pp_auto_ref:'',				 pp_sm_margin:0,
						pp_drill_margin:0,			 pp_work:'Features',
						pp_construct:'No',
					}
				});

				GEN.COM("filter_reset,filter_name=popup")
				GEN.COM("filter_set,filter_name=popup,update_popup=no,feat_types=surface")
				GEN.COM("sel_ref_feat,layers="+sm+",use=filter,mode=cover,pads_as=shape,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,include_syms=,exclude_syms=")
				GEN.COM("filter_reset,filter_name=popup")
				if(GEN.getSelectCount() > 0){
					GEN.selMoveOther({target_layer:'turn_pad_turn',invert:'no',dx:0,dy:0,size:0})
					GEN.workLayer({name:'turn_pad_turn',display_number:2,clear_before:'yes'})
					GEN.COM("sel_cont_resize,accuracy=0,break_to_islands=yes,island_size=0,hole_size=0,drill_filter=no,corner_ctl=yes")
					GEN.units({type:"inch"})
					GEN.COM("sel_cont2pad,match_tol=1,restriction=,min_size=0.01,max_size=100000,suffix=+++")
					GEN.selMoveOther({target_layer:sig,invert:'no',dx:0,dy:0,size:0})
					GEN.units({ type: par.units });
					GEN.deleteLayer({job:job, layer:["turn_pad_turn", "turn_pad_turn+++"]})
				}
				// if(GEN.getSelectCount()>0){
				// 	// 1. 将s*的转pad移回去
				// 	GEN.selMoveOther({target_layer:'turn_pad_temp',invert:'no',dx:0,dy:0,size:0})
				// 	GEN.workLayer({name:"turn_pad_temp",display_number:2,clear_before:'yes'})
				// 	GEN.selectByFilter({include_syms:"s*"})
				// 	if(GEN.getSelectCount()>0){
				// 		GEN.selMoveOther({target_layer:'turn_pad_turn',invert:'no',dx:0,dy:0,size:0})
				// 		GEN.workLayer({name:'turn_pad_turn',display_number:2,clear_before:'yes'})
				// 		GEN.COM("sel_cont_resize,accuracy=0,break_to_islands=yes,island_size=0,hole_size=0,drill_filter=no,corner_ctl=yes")
				// 		GEN.units({type:"inch"})
				// 		GEN.COM("sel_cont2pad,match_tol=1,restriction=,min_size=0.01,max_size=100000,suffix=+++")
				// 		GEN.selMoveOther({target_layer:sig,invert:'no',dx:0,dy:0,size:0})
				// 		GEN.units({ type: par.units });
				// 	}
				// 	GEN.workLayer({name:"turn_pad_temp",display_number:2,clear_before:'yes'})
				// 	// 将短线移回去
				// 	var Feats= GEN.getFeatures({job:job, step:step, layer: "turn_pad_temp", units:"mm", options:"feat_index"})
				// 	Feats.forEach(function(item){
				// 		if(item.type == "line"){
				// 			var linelength = Math.sqrt((item.xe-item.xs)*((item.xe-item.xs) +   (item.ye-item.ys)*(item.ye-item.ys)    ))*1000
				// 			if(linelength < 80 || linelength > 2000){
				// 				GEN.selLayerFeat({layer:"turn_pad_temp", index:item.index,operation:"select"})
				// 				GEN.selMoveOther({target_layer:sig,invert:'no',dx:0,dy:0,size:0})
				// 			}
				// 		}
				// 	})
				// 	// 将重复线移回去


				// 	GEN.selAllFeat() 
				// 	if(GEN.getSelectCount() > 0) {
				// 		GEN.selClearFeature()
				// 		IKM.msg("请选中需要转pad的物件,没有则不选")
				// 		GEN.displayLayer({name:sm,number:1})
				// 		GEN.PAUSE("check to turn pad")
				// 		// 手动选中
				// 		if(GEN.getSelectCount() > 0) {
				// 			// 将选中的转pad
				// 			GEN.selMoveOther({target_layer:'turn_pad_turn',invert:'no',dx:0,dy:0,size:0})
				// 			GEN.workLayer({name:'turn_pad_turn',display_number:2,clear_before:'yes'})
				// 			GEN.COM("sel_cont_resize,accuracy=0,break_to_islands=yes,island_size=0,hole_size=0,drill_filter=no,corner_ctl=yes")
				// 			GEN.units({type:"inch"})
				// 			GEN.COM("sel_cont2pad,match_tol=1,restriction=,min_size=0.01,max_size=100000,suffix=+++")
				// 			GEN.selMoveOther({target_layer:sig,invert:'no',dx:0,dy:0,size:0})
				// 			GEN.units({ type: par.units });
				// 		}
				// 		GEN.workLayer({name:"turn_pad_temp",display_number:2,clear_before:'yes'})
				// 		GEN.selMoveOther({target_layer:sig,invert:'no',dx:0,dy:0,size:0})
					
				// 	}
				// 	GEN.deleteLayer({job:job, layer:["turn_pad_temp+++","turn_pad_temp2","turn_pad_temp3"]})
				// }
				// if(GEN.isLayerExists({job:job, layer:"turn_pad_temp"})){GEN.deleteLayer({job:job, layer:"turn_pad_temp"})}
				// if(GEN.isLayerExists({job:job, layer:"turn_pad_temp+++"})){GEN.deleteLayer({job:job, layer:"turn_pad_temp+++"})}
				if(GEN.isLayerExists({job:job, layer:sm + "+++"})){GEN.deleteLayer({job:job, layer:sm + "+++"})}
				if(GEN.isLayerExists({job:job, layer:sig + "+++"})){GEN.deleteLayer({job:job, layer:sig + "+++"})}
				// GEN.deleteLayer({job:job, layer:[sm + "+++"]})
			})
		}

        GEN.clearLayers();
        GEN.affectedLayer({ mode: 'all', affected: 'no' });
    })

	//保存 
	if(/yes/ig.test(par.auto_save.toLowerCase())){  //
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}   
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}